package cn.itcast.kl.controller;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.itcast.kl.dto.ChuCangGoodsList;
import cn.itcast.kl.dto.AiSiOrder;
import cn.itcast.controller.IpBean;
import cn.itcast.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;

/**
 * 昆仑
 */
@RestController
@Slf4j
public class ChuCangController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    public  static volatile Map<String,IpBean> ret=new HashMap<>();
    @RequestMapping("/createKlMarket")
    public String createKlMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(list)){
            try{
                IpBean ipBean1 = new IpBean();
                ipBean1.setIpAddress("117.160.250.132");
                ipBean1.setPort(8080);
                list.add(ipBean1);
            }catch (Exception e){
                IpBean ipBean=new IpBean();
                list.add(ipBean);
            }
        }
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int j=0;j<list.size();j++){
                    for(int z=0;z<tokenList.size();z++){
                        IpBean ipBean=list.get(j);
                        String ips=null;
                        IpBean bean=null;
                        if(ret.containsKey("ip")){
                            bean=  ret.get("ip");
                            if(bean.getDate()<(new Date().getTime())){
//                                ips=HttpRequest.get("http://tiqu.pyhttp.taolop.com/getflowip?count=1&neek=70500&type=1&sep=1&sb=&ip_si=1&mr=0")
//                                        .execute().body();
                                bean.setIpAddress(ips);
                                bean.setDate(new Date().getTime()+2000);
                            }else{
                                ips=bean.getIpAddress();
                            }
                        }else{
                            bean=new IpBean();
//                            ips=HttpRequest.get("http://tiqu.pyhttp.taolop.com/getflowip?count=1&neek=70500&type=1&sep=1&sb=&ip_si=1&mr=0")
//                                    .execute().body();
                            bean.setIpAddress(ips);
                            bean.setDate(new Date().getTime()+2000);
                        }
                        ret.put("ip",ipBean);
//                        log.info("######请求ip返回数据####："+ips.trim());
//                        String str[]=ips.trim().split(":");
//                        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(str[0], Integer.parseInt(str[1])));
                        Proxy proxy=null;
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1000);
                    }

                }
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####热浪执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品数据异常####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        String result=null;
        try{
            Long time=System.currentTimeMillis();
            String sign= DigestUtil.md5Hex("goods_id="+goodsId+"&jin=1&limit=100&page=1&sort=1&time="+time+"&key=woshijiamijiekou").toUpperCase();
            result = HttpRequest.get("http://kl.suixingkeji.cn/data/api.auth.mark/getGoodsList?page=1&limit=100&sort=1&jin=1&goods_id="+goodsId+"&time="+time+"&sign="+sign)
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .setReadTimeout(5000)
                    .execute().body();
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(!StringUtils.isEmpty(result)){
            ChuCangGoodsList
                    siGoodsList= JSONUtil.toBean(result, ChuCangGoodsList.class);
            log.info("######获取商品数据成功#######"+siGoodsList.toString()+"##商品id###"+goodsId);
            if(siGoodsList.getData()!=null && !CollectionUtils.isEmpty(siGoodsList.getData().getData())){
                List<ChuCangGoodsList.ChuCangGoodsDetailList> list=siGoodsList.getData().getData();
                for(ChuCangGoodsList.ChuCangGoodsDetailList detailDTO:list){
                    if(new BigDecimal(detailDTO.getPrice()).compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
                        ThreadUtil.execAsync(() -> {
                            saveOrder(finalProxy,token,detailDTO);
                        });
                        Thread.sleep(1100);
                    }

                }
            }
        }else{
            log.info("##获取商品数据异常##");
        }
    }

    public void saveOrder(Proxy proxy, String token, ChuCangGoodsList.ChuCangGoodsDetailList detailDTO){

        String createResult=null;
        AiSiOrder aiSiOrder=null;
        String result=null;
        try {
            Long time=System.currentTimeMillis();
            String sign=DigestUtil.md5Hex("id="+detailDTO.getId()+"&key=woshijiamijiekou"+"&time="+time);
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", detailDTO.getId());
            paramMap.put("time", time);
            paramMap.put("sign", sign);
            result =
                    HttpRequest.post("http://kl.suixingkeji.cn/data/api.auth.mark/addOrder").form(paramMap).header("api-token",token).execute().body();
            aiSiOrder= JSONUtil.toBean(result, AiSiOrder.class);
            log.info("####支付结果######"+aiSiOrder.toString());
        } catch (Exception e) {
            log.info("####支付结果异常######"+e.getMessage()+":detailDTO"+detailDTO.toString());
        }
        if(null!=aiSiOrder && aiSiOrder.getCode()==1){
            //请求数据生成url连接
            log.error("####生成订单数据######"+aiSiOrder.getAiSiOrderDetail().getUrl());
            MailUtil.send("1027060531@qq.com", "昆仑支付", "艾斯您有一个昆仑新的订单，请赶紧支付！", false);
        }
    }
    public void addToken(){
        tokenList.add("72116e0a72a4a42e8fad80a362e1157d");
    }

}
